package com.ease.integration.ftp;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPListParseEngine;
import org.apache.commons.net.ftp.FTPReply;

import com.ease.common.util.Detect;

@Deprecated
/* refactor into FtpTemplate */
public class FtpUtil {

	private static final Log log = LogFactory.getLog(FtpUtil.class);

	public static boolean deleteFiles(String username, String password, String serverIp, String remotePath, List<String> fileNames) {
		FTPClient ftpClient = null;
		try {
			ftpClient = connectToFtpServer(username, password, serverIp);
			ftpClient.changeWorkingDirectory(remotePath);
			String[] fileNamesOnServer = ftpClient.listNames();
			if (Detect.notEmpty(fileNames) && Detect.notEmpty(fileNamesOnServer)) {
				for (int i = 0; i < fileNamesOnServer.length; i++) {
					if (-1 < Collections.binarySearch(fileNames, fileNamesOnServer[i])) {
						if (log.isDebugEnabled()) {
							log.debug("删除文件:" + fileNamesOnServer[i]);
						}
						ftpClient.dele(fileNamesOnServer[i]);
					}
				}
			}
			return true;
		} catch (Exception e) {
			log.error(e, e);
		} finally {
			disconnectFromFtpServer(ftpClient);
		}
		return false;
	}

	public static boolean getFile(String username, String password, String serverIp, String remotePath, List<String> fileNames, String localPath) {
		FTPClient ftpClient = null;
		FTPFile[] remoteFiles = null;

		try {
			ftpClient = connectToFtpServer(username, password, serverIp);
			ftpClient.changeWorkingDirectory(remotePath);
			remoteFiles = ftpClient.listFiles();

			if (null != remoteFiles) {
				for (FTPFile ftpFile : remoteFiles) {
					if (-1 < Collections.binarySearch(fileNames, ftpFile.getName())) {
						File localFile = new File(localPath + File.separator + ftpFile.getName());
						FileOutputStream fos = null;
						try {
							fos = new FileOutputStream(localFile);
							ftpClient.retrieveFile(ftpFile.getName(), fos);
						} catch (Exception e) {
							log.error(e, e);
						} finally {
							if (null != fos) {
								try {
									fos.close();
								} catch (IOException e) {
									log.error(e, e);
								}
								fos = null;
							}
						}
					}
				}
			}
			return true;
		} catch (Exception e) {
			log.error(e, e);
		} finally {
			disconnectFromFtpServer(ftpClient);
		}
		return false;
	}

	public static List<String> listFiles(String username, String password, String serverIp, String remotePath) {
		int fileCacheSize = 5;
		FTPClient ftpClient = null;
		List<String> fileNames = new ArrayList<String>();
		try {
			ftpClient = connectToFtpServer(username, password, serverIp);
			FTPListParseEngine f = ftpClient.initiateListParsing(remotePath);
			while (null != f && f.hasNext()) {
				FTPFile[] files = f.getNext(fileCacheSize);
				for (FTPFile file : files) {
					fileNames.add(file.getName());
				}
			}
		} catch (Exception e) {
			log.error(e, e);
		} finally {
			disconnectFromFtpServer(ftpClient);
		}
		return fileNames;
	}

	public static boolean putFile(String username, String password, String serverIp, String localPath, List<String> fileNames, String remotePath) {
		FTPClient ftpClient = null;
		FileInputStream in = null;

		if (Detect.notEmpty(fileNames)) {
			try {
				ftpClient = connectToFtpServer(username, password, serverIp);
				ftpClient.changeWorkingDirectory(remotePath);
				for (String fileName : fileNames) {
					try {
						in = new FileInputStream(new File(localPath + File.separator + fileName));
						ftpClient.storeFile(fileName, in);
					} catch (Exception e) {
						log.error(e, e);
						return false;
					} finally {
						if (null != in) {
							try {
								in.close();
							} catch (IOException e) {
								log.error(e, e);
								in = null;
							}
						}
					}
				}
				return true;
			} catch (Exception e) {
				log.error(e, e);
				return false;
			} finally {
				disconnectFromFtpServer(ftpClient);
			}
		}
		return false;
	}

	private static FTPClient connectToFtpServer(String username, String password, String serverIp) throws Exception {
		FTPClient ftpClient = null;
		try {
			ftpClient = new FTPClient();
			ftpClient.setControlEncoding("GBK");
			ftpClient.connect(serverIp);
			ftpClient.login(username, password);
			ftpClient.enterLocalPassiveMode();
			int returnCode = ftpClient.pasv();
			returnCode = ftpClient.getReplyCode();
			ftpClient.setDataTimeout(10000);
			if (!FTPReply.isPositiveCompletion(returnCode)) {
				if (log.isDebugEnabled()) {
					log.debug("FTP server refused connection.returnCode=" + returnCode);
				}
				throw new Exception("FTP server refused connection.returnCode=" + returnCode);
			}
			if (log.isDebugEnabled()) {
				log.debug("connected to FTP server. ip=" + serverIp);
			}
			return ftpClient;
		} catch (Exception e) {
			log.error(e, e);
			try {
				ftpClient.disconnect();
			} catch (IOException e1) {
				ftpClient = null;
				throw new Exception(e);
			} finally {

			}
		}
		return ftpClient;
	}

	private static void disconnectFromFtpServer(FTPClient ftpClient) {
		if (null != ftpClient) {
			try {
				ftpClient.logout();
				ftpClient.disconnect();
			} catch (IOException e) {
				log.error(e, e);
			} finally {
				ftpClient = null;
			}
		}
	}
}
